package com.hui.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 李昭辉
 * @Date: 2021/07/09/9:28
 * @Description: 监听器，统计在线人数
 */
public class TotalOnlinePerson implements HttpSessionListener, ServletContextListener {
    // 保存全局的ServletContext
    private ServletContext context;

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        // 初始化context
        context = servletContextEvent.getServletContext();
        context.setAttribute("count", 0);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        context = null;
    }

    // 新增一个session，用户+1
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        Integer count = (Integer) context.getAttribute("count");
        context.setAttribute("count", ++count);
    }

    // 销毁一个session，用户-1
    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        Integer count = (Integer) context.getAttribute("count");
        context.setAttribute("count", --count);
    }
}
